<style scoped lang="scss">

</style>


<template>
  <div class="app-container">
    <div style="padding: 20px 20px 0 20px;">
      授权角色{{$route.query.roleName}}
    </div>
    <el-tree
      style="margin: 20px 0"
      ref="tree"
      :data="roleAllMenu"
      node-key="id"
      show-checkbox
      default-expand-all
      :default-checked-keys="selectedKeys"
      :props="defaultProps"
      @check-change="onCheckChange"
    />
    <div style="padding: 20px 20px;">
      <el-button :loading="loading" type="primary" icon="el-icon-check" size="mini" @click="save">保存</el-button>
      <el-button @click="$router.push('/system/sysRole')" size="mini" icon="el-icon-refresh-right">返回</el-button>
    </div>
  </div>
</template>

<script lang="js">
import api from '@/api/role/role';

export default {
  data() {
    return {
      loading: false,
      roleAllMenu: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      selectedKeys: []
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      api.toAssign(this.$route.query.id).then(response => {
        const roleAllMenu = response.data;
        this.roleAllMenu = roleAllMenu;
        console.log(this.roleAllMenu);
        this.selectedKeys = this.getCheckedId(roleAllMenu);
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(this.selectedKeys);
        });
      });
    },
    getCheckedId(auth, initArr = []) {
      return auth.reduce((pre, item) => {
        if (item.select && item.children.length === 0) {
          pre.push(item.id);
        } else if (item.children) {
          pre.push(...this.getCheckedId(item.children, initArr));
        }
        return pre;
      }, []);
    },
    onCheckChange(node, checked) {
      // 更新节点的 .select 状态
      node.select = checked;
      console.log('节点:', node, '选中状态:', checked);
    },
    save() {
      const allCheckedNodes = this.$refs.tree.getCheckedNodes(false, true);
      let idList = allCheckedNodes.map(node => node.id);
      let assignMenuVo = {
        roleId: this.$route.query.id,
        roleMenuIds: idList
      };
      api.doAssign(assignMenuVo).then(response => {
        this.loading = true;
        this.$message.success(response.message || '分配成功');
        this.$router.push('/system/sysRole');
      });
    }
  }
};
</script>
